package demo.practice.top100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class P39 {

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> list = new ArrayList<>();
        Arrays.sort(candidates);
        dfs(list, target, candidates, new ArrayList<>(),0);
        return list;
    }

    /**
     *
     * @param list
     * @param target
     * @param candidates
     * @param l
     * @param start
     */
    public void dfs(List<List<Integer>> list, int target, int[] candidates, List<Integer> l, int start) {
        if (target == 0) {
            list.add(l);
        }
        for (int i = start; i < candidates.length; i++) {
            if (candidates[i] > target) {
                return;
            }
            if (i - 1 >= 0 && candidates[i] == candidates[i - 1]) continue;
            ArrayList<Integer> c = new ArrayList<>(l);
            c.add(candidates[i]);
            dfs(list, target - candidates[i], candidates, c, i);
        }
    }
}
